"use strict";
const tool = require("./tool");
const config = require("../config");

const logined = (req, res, next) => {
  const client = tool.getResponseFunc(res);
  if (req.session.account) {
    next();
  } else {
    client.fail(new Error("e_login"));
  }
}

const isAdmin = (req, res, next) => {
  if (req.session.account.isAdmin) {
    next();
  } else {
    const client = tool.getResponseFunc(res);
    client.fail(new Error("50004"));
  }
}

const hashSha256 = function(raw) {
	const sha256 = require("crypto").createHash("sha256");
	let result = [];
	let total = 0;

	sha256.setDefaultEncoding("utf-8");
	sha256.end(raw);
	sha256.on("data", buffer => {
		result.push(buffer);
		total += buffer.length;
	});
	return new Promise((success, fail) => {
		sha256.on("end", () => {
			const str = Buffer.concat(result, total).toString("hex");
			//console.log("读取完毕，sha256之后的数据是", str);
			success(str);
		});
		sha256.on("error", e => {
			console.error("sha256出错", e);
			fail(e);
		});
	});
};

const isFalsified = function(req, res, next) {
	if (!config.encrypt) {
		next();
		return;
	}
	const escapeChar = function() {
		req.body = tool.escapeObj(req.body);
	};
	const client = tool.getResponseFunc(res);
	const compareTo = req.get("expire-day");
	if (!compareTo) {
		console.error("没有检验头", req.originalUrl);
		client.fail(new Error("e_falsified"));
		return;
	}
	const text = Object.keys(req.body).length ?
		JSON.stringify(req.body) :
    "";
  const { basePath } = config;
  let originalUrl = req.originalUrl;
  if (basePath !== '/') originalUrl = originalUrl.replace(basePath, '');
  const raw = text + decodeURI(originalUrl) + "KGDUTERPYEG";

	return hashSha256(raw)
		.then(afterHash => {
			if (afterHash !== compareTo) {
				console.error("企图攻击？！", req.originalUrl, afterHash, compareTo);
				const e = new Error("e_falsified");
				client.fail(e);
				throw e;
			}
		})
		.then(escapeChar)
		.then(next);
};

module.exports = {
  logined,
  isAdmin,
  isFalsified,
}
